package cn.com.nes.site.module.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import cn.com.nes.common.util.DBUtils;
import cn.com.nes.site.entity.sms.VerCodeReq;

@Repository
public class UserConnDaoImpl extends BaseConnDaoImpl {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public boolean checkPhone(String phone) throws SQLException  {
		Connection conn = null ;
		StringBuffer sb = new StringBuffer();
		int i = 0;
		try {
			conn =DBUtils.getJNDIDBConn() ;
			
			i = queryForInt(conn,"select if(count(0) is null,0,count(0)) from t_user where (username = ? or phone=? ) and sfsc=0",
					new Object[] { phone, phone});
		}catch (Exception e) {
		}finally {
			if(conn!=null) conn.close();
		}
		
		if (i > 0)
			return true;
		else
			return false;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public int InsertSmsCode(VerCodeReq sms) throws SQLException  {
		Connection conn = null ;
		StringBuffer sb = new StringBuffer();
		int i = 0;
		try {
			conn =DBUtils.getJNDIDBConn() ;
			i = update(conn,"insert into t_sms (smstype,phone,VerCode,createTime,dateline) values(?,?,?,now(),DATE_ADD(now(),INTERVAL 5 minute))",
					new Object[] { sms.getSmstype(),
							sms.getPhone(), sms.getVercode()});
			if(i>0) {conn.commit();}
		}catch (Exception e) {
		}finally {
			if(conn!=null) {
				conn.rollback();
				conn.close();
			} 
		}
		return i;
	}
	

	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public long VerificationCode(String phone,String code) throws SQLException  {
		Connection conn = null ;
		StringBuffer sb = new StringBuffer();
		List<Map<String, Object>> list = null ;
		long i = 0;
		try {
			conn =DBUtils.getJNDIDBConn() ;
			list = queryForList(conn,
					"select  TIME_TO_SEC(TIMEDIFF(max(dateLine),now())) as seconds from t_sms where   smstype= ? and phone = ? and vercode = ?",
					new Object[] { "2", phone,code });
			if (list.size()>0) {
				i=(long)list.get(0).get("seconds");
			}else {
				i=0;
			}
			
		}catch (Exception e) {
		}finally {
			if(conn!=null) conn.close();
		}
		
		return i;
	}
}